<template>
    <div id="message">
        <div v-if="isShadow" class="shadow">
            <div class="percent"><b-progress v-model="percent" :max="max" show-progress animated></b-progress></div>
        </div>
        <b-form>
            <!-- 头像部位，暂时不知道怎么实现文件上传 -->
            <div>
                <img id="mHeadPor" :src="img" width="60" height="60">
                <b-form-file class="mt-3" browse-text="浏览图片" v-model="file" plain></b-form-file>
            </div>
            <!-- 信息 -->
            <b-form-group v-for="(item, index) in items" :key="index"
                class="mList"
                :label="item.name"
            >
            
            <!--
                1. ref随着数组改变，以作区分
                2. 更具数据设置输入框为仅可读状态（readOnly）
            -->
                <b-form-input
                    :ref="'miInput'+ index"
                    :type="item.type"
                    :readonly= "item.readOnly"
                    v-model="item.value"
                ></b-form-input>                        
            </b-form-group>
            <!-- 
                1. readOnly 状态没有修改按钮
                2. 监听点击事件
            -->
            <b-button letiant="primary" variant="primary" @click="userModify()">更改</b-button>
        </b-form>
    </div>
</template>

<script>
import store from '@/store/index.js';
import { pictureToken, updateUser } from '@/../api/api.js'
import { getBlob } from '@/../api/index.js'
import Axios from 'axios';
import * as qiniu from 'qiniu-js';
export default {
    data() {
        return {
            // 数据格式
            items: {
                name:{
                    readOnly: false,
                    name: "用户昵称",
                    value: store.state.user.user.name,
                    type:'text'
                },
                career:{
                    readOnly: false,
                    name: "职业",
                    value: store.state.user.user.career,
                    type:'text'
                },
                education:{
                    readOnly: false,
                    name: "学历",
                    value: store.state.user.user.education,
                    type:'text'
                },
                major:{
                    readOnly: false,
                    name: "技术类别",
                    value: store.state.user.user.major,
                    type:'text'
                },
                gender:{
                    readOnly: false,
                    name: "性别(0-男 1-女)",
                    value: (store.state.user.user.gender == '男') ? 0:1,
                    type:'number'
                },
                birth:{
                    readOnly: false,
                    name: "出生日期",
                    value: store.state.user.user.birth ? (new Date(store.state.user.user.birth).getFullYear()+'-'+(new Date(store.state.user.user.birth).getMonth()+1)+'-'+new Date(store.state.user.user.birth).getDay()):null,
                    type:'date'
                },
                brief:{
                    readOnly: false,
                    name: "个人简介",
                    value: store.state.user.user.brief,
                    type:'text'
                },
            },
            img: store.state.user.user.avatar,
            file:{},
            value: '',
            context: null,
            percent:1,
            max:100,
            isShadow:false
        }
    },
    methods: {
        onContext(ctx) {
            this.context = ctx;
        },
        userModify() {
            let tip = 0;
            let repetition =0;
            let linshi;
            for (let element in this.items) {
                if (this.items[element].value == '' && element != 'name') {
                    this.items[element].value = null;
                }
                if(/^[\u4E00-\u9FA5A-Za-z0-9_,.?!，。？！…-]+$/.test(this.items[element].value)) {
                    this.$refs["miInput" + element][0].state = true;
                    setTimeout(() => {
                        this.$refs["miInput" + element][0].state = null;
                    }, 2000)
                }else{
                    this.$refs["miInput" + element][0].state = false;
                    tip++;
                } 
            }
            if (this.items.gender.value>=2 || this.items.gender.value<0) {
                this.$refs["miInputgender"][0].state = false;
                tip++;
            }
            if (tip === 0) {
                for (let element in this.items) {
                    if (element == 'gender') {
                        this.items[element].value = this.items[element].value == 0 ? '男':'女';
                    }
                    if (element == 'birth') {
                        this.items[element].value = new Date(this.items[element].value);
                    }
                    linshi=this.items[element].value;
                    store.commit('updateUserOnes',{
                        value: linshi,
                        tips:element
                    });
                }
                if (this.img != store.state.user.user.avatar) {
                    this.isShadow = true;
                    Axios.get(pictureToken)
                    .then(Response => {  
                        if (Response.data.message == 'success') {
                            let file = getBlob(this.img);
                            let config = {
                                useCdnDomain: true,   
                                region: null
                            };
                            let putExtra = {
                                fname: this.file.name,  
                                params: {}, 
                                mimeType: ["image/png", "image/jpeg", "image/gif","image/jpg"]
                            };
                            let observable = qiniu.upload(file, this.file.name, Response.data.data.token, putExtra, config);
                            observable.subscribe({
                                next: (result) => {
                                    this.percent = parseInt(result.total.percent);
                                },
                                error: (errResult) => {
                                    console.log(errResult)
                                },
                                complete: (result) => {
                                    let url = 'http://img.sharpfactory.top/'+ result.key;
                                    store.commit('updateUserOnes',{
                                        value: url,
                                        tips: 'avatar'
                                    });
                                    Axios.post(updateUser,{
                                        user:store.state.user.user
                                    })
                                    .then(Response => {
                                        if (Response.data.message == 'success') {
                                            this.percent = 99;
                                            this.isShadow = false;
                                            window.alert("保存成功");
                                            this.$router.push({
                                                path:'/personalblog'
                                            });
                                        }
                                    })
                                    .catch(err => {
                                        console.log(err);
                                    });
                                }
                            });
                        } else if(Response.data.message == 'tokenGuard') {
                            this.isShadow = false;
                            window.alert("已超过每天最大图片上传次数");
                        } 
                    })
                    .catch(err => {
                        console.log(err);
                    });
                } else {
                    Axios.post(updateUser,{
                        user:store.state.user.user
                    })
                    .then(Response => {
                        if (Response.data.message == 'success') {
                            window.alert("保存成功");
                            this.$router.push({
                                path:'/personalblog'
                            });
                        }
                    })
                    .catch(err => {
                        console.log(err);
                    });
                }
                
            }
            else {
                window.alert("输入字符不规范，请重新更改后提交");
            }
        }
    },
    watch: {
        file(newValue,oldValue) {
            if (newValue != null) {
                if (newValue.type.split('/')[0] == "image") {
                    if (newValue.size <= 3145728) {
                        let reader = new FileReader();
                        reader.readAsDataURL(newValue,"UTF-8");
                        reader.onload = res => {
                            this.img = res.target.result;
                        };
                    } else {
                        window.alert("图片大小不得超过3M！");
                        this.file = null;
                    }
                } else {
                    window.alert("请选择正确的图片格式！");
                    this.file = null;
                }
            } else {
                this.img = store.state.user.user.avatar;
            }
        },
    },
}
</script>

<style lang="stylus" scoped>
.shadow
    width 100%;
    height 100%;
    position fixed;
    left 0;
    top 0;
    z-index 998;
    background-color #000;
    opacity 0.6;
.percent
    z-index 999;
    width 600px;
    margin 25% 27%;
#message
    width 500px
    right 50%
    margin-left 30%
#mHeadPor
    border-radius 50%

.mList
    margin-top 20px
    button
        margin-top 6px
</style>